package com.fragrance.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.fragrance.service.WeChatApiService;
import com.fragrance.service.impl.WeChatApiServiceImpl;
import com.fragrance.util.Constants;
import com.jfinal.core.Controller;

public class WeChatOpenUserController extends Controller {

	private Logger logger = LoggerFactory.getLogger(WeChatOpenUserController.class);

	private WeChatApiService weChatService = new WeChatApiServiceImpl();
	/**
	 * 微信用戶登录
	 */
	public void weChatUserLogin() {
		String code = getPara("code");
//		String encryptedData = getPara("encryptedData");
//		String iv = getPara("iv");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(code)) {
			logger.info("code不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
//		if (StringUtils.isEmpty(encryptedData)) {
//			logger.info("encryptedData不能为空");
//			result.put("code", Constants.PARAM_VAILD_CODE);
//			result.put("msg", Constants.PARAM_VAILD_MSG);
//			renderJson(result);
//			return;
//		}
//		if (StringUtils.isEmpty(iv)) {
//			logger.info("iv不能为空");
//			result.put("code", Constants.PARAM_VAILD_CODE);
//			result.put("msg", Constants.PARAM_VAILD_MSG);
//			renderJson(result);
//			return;
//		}
		try {
			result = weChatService.getOpenId(code);
			logger.info("result = "+ JSON.toJSONString(result));
		} catch (Exception e) {
			logger.error("微信用户登录失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
		}
		renderJson(result);
	}
}